#!/usr/bin/env groovy
package com.yidao.www

def javaAutoBuild(project, branch, language, webhookUrl, profile, packageType){

    def buildProfile = buildProfile(project, branch)
    def date = new Date()

    def label = buildProfile.label + '_' + BUILD_NUMBER
    def image = buildProfile.image
    def gitUrl = buildProfile.gitUrl
    def buildTool = buildProfile.buildTool
    def pom = buildProfile.pom
    def buildFile = buildProfile.buildFile
    def artifactDir = buildProfile.artifactDir
    def artifactName = buildProfile.artifactName
    def artifact =  artifactDir + artifactName
    def artifactTar = artifactDir + buildProfile.artifactTar
    def artifactory = buildProfile.artifactory
    def base = new base()
    def notification = new notification()
    def jobName = JOB_NAME
    def buildNumber = BUILD_NUMBER
    def jobUrl = JOB_URL
    def logUrl = BUILD_URL + 'console'
    def username = ''
    def deployTarget = base.backupFolder(artifactory, project, branch, date)
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url
    def storageURL = srverUrl + '/' + deployTarget

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins',
        volumes: [hostPathVolume(hostPath: '/data/nfs/workspace/m2', mountPath: '/home/jenkins/.m2')]) {
            node(label){

                stage('checkout'){
                    try{
                        base.gitClone(gitUrl, branch)
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('package'){
                    try{
                        if(buildTool == 'maven'){
                            base.mavenPackage(pom, profile)
                        }else if(buildTool == 'gradle'){
                            base.gradleBuild(buildFile)
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '打包失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }

                }

                stage('archive'){
                    // base.archive(artifact)
                }

                stage('deploy to artifactory'){
                    print 'deploy ...'
                    print '================='
                    print artifact
                    print deployTarget
                    print '================='
                    try{
                        base.fileUpload(artifactTar, deployTarget)
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '上传失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('deploy to server'){
                    print 'deploy ...'
                    print deployProfile(project)
                    try{
                        if(packageType == 'jar'){
                            echo "jar 包部署"
                            base.mavenDeploy(project, artifact, artifactName)
                        }else if(packageType == 'war'){
                            echo "war 包部署"
                            base.tomcatDeploy(project, artifact, artifactName)
                        }

                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '部署失败，请检查服务器连接!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }


                }

                stage('notification'){
                    notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', currentBuild.currentResult)
                }

                stage('influxDb'){
                    currentBuild.result = 'SUCCESS'
                    currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                    base.influxDb()
                }

            }
        }

}

def javaManuallyBuild(project, branch, language, webhookUrl, profile, version){
    def buildProfile = buildProfile(project, branch)
    def date = new Date()

    def label = buildProfile.label + '_' + BUILD_NUMBER
    def image = buildProfile.image
    def gitUrl = buildProfile.gitUrl
    def buildTool = buildProfile.buildTool
    def pom = buildProfile.pom
    def buildFile = buildProfile.buildFile
    def verFile = buildProfile.verFile
    def ansible = buildProfile.ansible
    def tag = buildProfile.tag
    def artifactDir = buildProfile.artifactDir
    def artifactName = buildProfile.artifactName
    def artifact =  artifactDir + artifactName
    def artifactTars = buildProfile.artifactTar
    def artifactory = buildProfile.artifactory
    def base = new base()
    def ansibleBuild = new ansibleBuild()
    def notification = new notification()
    def jobName = JOB_NAME
    def buildNumber = BUILD_NUMBER
    def jobUrl = JOB_URL
    def logUrl = BUILD_URL + 'console'
    def username = ''
    def deployTarget = base.backupFolder(artifactory, project, branch, date)
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url

    def storageURL
    def versionInfo
    if(version){
        versionInfo = version + '.' + date.format('yyyyMMddHHmm') + '_' + buildNumber
        println  " versionInfo is :  " + versionInfo
    }else{
        versionInfo = project + '_' + branch + '_' + buildNumber
    }

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins',
        volumes: [hostPathVolume(hostPath: '/data/nfs/workspace/m2', mountPath: '/home/jenkins/.m2')]) {

            node(label){

                stage('checkout'){
                    storageURL = srverUrl + '/' + deployTarget
                    try{
                        base.gitClone(gitUrl, branch)
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('package'){
                    if(verFile){
                        def ver = "版本号:\n${versionInfo}\n编译日期:\n${date}"
                        base.writeFile(ver, verFile)
                    }
                    try{
                        if(buildTool == 'maven'){
                            base.mavenPackage(pom, profile)
                        }else if(buildTool == 'gradle'){
                            base.gradleBuild(buildFile)
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '打包失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }

                }

                stage('archive'){
                    // base.archive(artifact)
                }

                stage('deploy to artifactory'){
                    print 'deploy ...'
                    print '================='
                    print artifact
                    print deployTarget
                    print '================='
                    if(ansible){
                        ansibleBuild.autoDeploy(tag)
                    }
                    try{
                        base.multiFilesUpload(artifactTars, deployTarget)
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '上传失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('notification'){
                    notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', currentBuild.currentResult)
                }

                stage('influxDb'){
                    currentBuild.result = 'SUCCESS'
                    base.influxDb()
                }

                stage('retrun artifact'){
                    currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                    return deployTarget
                }

            }
        }

}

def submoduleAutoBuild(project, branch, language, webhookUrl, profile, buildTask, manuallyTrigger){
    def buildProfile = buildProfile(project, branch)
    def date = new Date()

    def label = buildProfile.label + '_' + BUILD_NUMBER
    def image = buildProfile.image
    def gitUrl = buildProfile.gitUrl
    def buildTool = buildProfile.buildTool
    def pom = buildProfile.pom
    def buildFile = buildProfile.buildFile
    def verFile = buildProfile.verFile
    def artifactDir = buildProfile.artifactDir
    def artifactName = buildProfile.artifactName
    def artifact =  artifactDir + artifactName
    def artifactTar = artifactDir + buildProfile.artifactTar
    def artifactory = buildProfile.artifactory
    def base = new base()
    def notification = new notification()
    def jobName = JOB_NAME
    def buildNumber = BUILD_NUMBER
    def jobUrl = JOB_URL
    def logUrl = BUILD_URL + 'console'
    def username = ''
    def deployTarget = base.backupFolder(artifactory, project, branch, date)
    def versionInfo = project + '_' + branch + '_' + buildNumber
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url
    def storageURL

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins',
        volumes: [hostPathVolume(hostPath: '/data/nfs/workspace/m2', mountPath: '/home/jenkins/.m2'),
                  hostPathVolume(hostPath: '/data/nfs/workspace/gradle/cache', mountPath: '/home/jenkins/.gradle')]) {

            node(label){

                stage('checkout'){
                    storageURL = srverUrl + '/' + deployTarget
                    currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                    try{
                        if(manuallyTrigger){
                            base.submoduleCheckout(gitUrl, branch)
                        }else{
                            base.submoduleGerritCheckout(gitUrl, branch)
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('package'){
                    if(verFile){
                        def ver = "版本号:\n${versionInfo}\n编译日期:\n${date}"
                        base.writeFile(ver, verFile)
                    }
                    try{
                        if(buildTool == 'maven'){
                            base.mavenPackage(pom, profile)
                        }else if(buildTool == 'gradle'){
                            base.gradleBuildScript(buildFile, buildTask)
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '打包失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }

                }

                stage('archive'){
                    // base.archive(artifact)
                }

                stage('deploy to artifactory'){
                    print 'deploy ...'
                    print '================='
                    print artifact
                    print deployTarget
                    print '================='
                    try{
                        base.fileUpload(artifactTar, deployTarget)
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '上传失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('notification'){
                    // notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', currentBuild.currentResult)
                }

                stage('influxDb'){
                    currentBuild.result = 'SUCCESS'
                    base.influxDb()
                }

                stage('retrun artifact'){
                    currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                    return deployTarget
                }

            }
        }

}


def wheelsAutoDeploy(project, branch, webhookUrl){
    def buildProfile = buildProfile(project, branch)
    def date = new Date()

    def label = buildProfile.label + '_' + BUILD_NUMBER
    def image = buildProfile.image
    def gitUrl = buildProfile.gitUrl
    def buildTool = buildProfile.buildTool
    def submodule = buildProfile.submodule
    def base = new base()
    def notification = new notification()
    def jobName = JOB_NAME
    def buildNumber = BUILD_NUMBER
    def jobUrl = JOB_URL
    def logUrl = BUILD_URL + 'console'
    def username = ''

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins',
        volumes: [hostPathVolume(hostPath: '/data/nfs/workspace/m2', mountPath: '/home/jenkins/.m2'),
                  hostPathVolume(hostPath: '/data/nfs/workspace/gradle/cache', mountPath: '/home/jenkins/.gradle')]) {

            node(label){

                stage('checkout'){
                    try{
                        if(submodule){
                            base.submoduleCheckout(gitUrl, branch)
                        }else{
                            base.gitClone(gitUrl, branch)
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                stage('deploy'){
                    try{
                        if(buildTool == 'maven'){
                            base.mavenDeploy(pom)
                        }else if(buildTool == 'gradle'){
                            base.gradleDeploy()
                        }
                    }catch(e){
                        notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', 'FAILURE')
                        println '编译失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }

                }

                stage('notification'){
                    // notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', currentBuild.currentResult)
                }

                stage('influxDb'){
                    currentBuild.result = 'SUCCESS'
                    base.influxDb()
                }

            }
        }

}